/**
 * 控制器原理
 * 1.定时器
 * 2.存储按键
 * 3.定时器到时刷新,位置按方向变更
 * 4.ui刷新到新位置
 * 5.判断是否异常
 * 6.升级或结束
 * 
 * 结构
 * 1.蛇
 * 2.食物
 * 3.等级管理
 */
import Snake  from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";

export class GameControl {
    isLive = true;
    step = 10;
    direction: string = "";//按键方向
    snake:Snake;
    food:Food;
    scorePanel:ScorePanel;


    //游戏处理
    constructor() {
        this.snake = new Snake();
        this.food = new Food();
        this.scorePanel = new ScorePanel(10,3);
        this.init();//ts 严格检查，需要写明this
    }

    init() {
        // document.addEventListener('keydown',function(ev:KeyboardEvent){
        //     // this 这里是 指的document
        // })

        document.addEventListener('keydown', this.keydownHandler.bind(this));//this重定向，指向传入的对象，this是当前对象

        this.run();
    }

    keydownHandler(event: KeyboardEvent) {
        console.log("收到按键事件"+event.key)
        this.direction = event.key
    }

    run() {
        console.log("run")
        let x = this.snake.X;
        let y = this.snake.Y;
        //蛇前进,转向
        switch (this.direction) {
            case "ArrowUp":
                y -= this.step;
                break;
            case "ArrowDown":
                y += this.step;
                break;
            case "ArrowLeft":
                x -= this.step;
                break;
            case "ArrowRight":
                x += this.step;
                break;
        }

        this.checkEat();

        try{

            //snake 中 set、get 会进行相关判断
            this.snake.X = x;
            this.snake.Y = y;

        }catch(e){
            //抛出异常，游戏结束
            // @ts-ignore
            alert(e.message);
            window.location.reload();
            this.isLive = false;
        }
        //1.设置定时器,时间需要根据等级动态变化，越来越快
        this.isLive && setTimeout(this.run.bind(this),200 -  (this.scorePanel.level - 1)*30)

    }

    checkEat(){
        if(this.snake.X === this.food.X && this.snake.Y === this.food.Y){
            this.food.refreshPosition();
            this.snake.addBody();
            this.scorePanel.addCore();
        }
        
    }

    
}
